const express = require('express');
const router = express.Router();

const jwt = require('jsonwebtoken');
const {JWTconfig} = require('../config'); // 引入配置文件
const {findUser,insertUser,findUserByPassword} = require('../dataBase/api'); // 引入数据库操作方法


// Login route
router.post('/',async (req, res) => {
    const { username, password } = req.body;

    // Find user
     const users = await findUserByPassword([username, password]);
     console.log('users',users);
    const user = users.find(u => u.username === username && u.password === password);

    if (!user) {
        return res.success(null,'用户名或密码错误' , 500);
    }

    // 生成 token
    const token ='Bearer ' + jwt.sign({ id: user.id, username: user.username }, JWTconfig.jwtSecretKey, { expiresIn: JWTconfig.expiresIn });

    res.success({ token:token,user:user });
});

//根据传过来的username进行查询数据库是否存在，否则就插入数据
router.post('/register',async (req, res) => {
    const { username, phone } = req.body;

    // Find user
    const users = await findUser(username);
    console.log('users',users);
    const user = users.find(u => u.username === username);

    if (user) {
        return res.success(null,'用户名已存在' , 500);
    }

    // Insert new user
    const newUser = await insertUser([username, phone]);
    console.log('newUser',newUser);
    
    res.success(newUser);
});


module.exports = router;